package com.ffms.servlet; /**
 * @author 从卿
 * @create 2022/3/8-1:10
 */

import com.ffms.dao.ShouruDao;
import com.ffms.dao.impl.FamilyMemberDaoImpl;
import com.ffms.dao.impl.ShouruDaoImpl;
import com.ffms.dao.impl.ZhiChuDaoImpl;
import com.ffms.entity.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet("/TjServlet")
public class TjServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        ShouruDao shouruDao = new ShouruDaoImpl();
        List<Shouru> shouruList = shouruDao.tj();
        Map<Integer, String> shouruMap = shouruList.stream().collect(Collectors.toMap(Shouru::getMssid, Shouru::getMoney));
        ZhiChuDaoImpl zhiChuDaoImpl = new ZhiChuDaoImpl();
        List<ZhiChu> zhiChus = zhiChuDaoImpl.tj();
        Map<Integer, String> zhiChuMap = zhiChus.stream().collect(Collectors.toMap(ZhiChu::getMzsid, ZhiChu::getMoney));

        FamilyMemberDaoImpl familyMemberDao = new FamilyMemberDaoImpl();
        List<FamilyMember> all = familyMemberDao.findAll();
        List<Tj> tjs = new ArrayList<>();
        double sr = 0;
        double zc = 0;

        for (FamilyMember familyMember : all) {
            String shouruAll = shouruMap.getOrDefault(familyMember.getSid(), "0");
            sr += Double.parseDouble(shouruAll);
            String zhichuAll = zhiChuMap.getOrDefault(familyMember.getSid(), "0");
            zc += Double.parseDouble(zhichuAll);
            Tj tj = new Tj(familyMember.getName(), shouruAll, zhichuAll);
            tjs.add(tj);
        }

        request.setAttribute("tjs", tjs);
        request.setAttribute("sr", sr);
        request.setAttribute("zc", zc);
        request.getRequestDispatcher("/admin/tj.jsp").forward(request, response);
    }
}
